package 字典树;

/**
 * 字典树
 *
 * @author idea
 * @data 2020/1/30
 */
public class TrieDemo {

    private TrieNode root=new TrieNode('/');

    public void insert(char[] text){
        TrieNode p = root;
        for(int i=0;i<text.length;i++){
            int index = text[i] - 'a';
            if(p.children[index] == null){
                TrieNode newNode = new TrieNode(text[i]);
                p.children[index] = newNode;
            }
            p=p.children[index];
        }
        p.isEndingChar=true;
    }


    public boolean find(char[] pattern){
        TrieNode p =root;
        for(int i=0;i<pattern.length;i++){
            int index=pattern[i]-'a';
            if(p.children[index]==null){
                return false;
            }
            p=p.children[index];
        }
        if(p.isEndingChar){
            return true;
        }
        return false;
    }



    public class TrieNode{
        public char data;
        public TrieNode[] children=new TrieNode[20];
        public boolean isEndingChar = false;

        public TrieNode(char data) {
            this.data = data;
        }
    }

    public static void main(String[] args) {
        TrieDemo trieDemo=new TrieDemo();
        trieDemo.insert(new char[]{'h','i','a','b'});
        boolean result = trieDemo.find(new char[]{'h'});
        System.out.println(result);
    }

}
